<template>
  <div class="delegation-modal" v-if="show" @click.self="close">
    <div class="delegation-content" 
         :style="popupStyle"
         :class="{ 'delegation-content--expanded': isExpanded }">
      <div class="delegation-header">
        <span class="delegation-close-btn" @click="close">×</span>
      </div>
      
      <div class="delegation-body">
        <div class="address-container">
          <div class="address-block">
            <img 
              src="../assets/icons/aimpoint.svg" 
              alt="定位" 
              class="address-icon"
              @error="handleImageError" 
              ref="addressIcon"
            />
            <div class="address-text">
              <div class="address-label">出发地</div>
              <div class="address-detail">{{ delegation.pickup_address }}</div>
            </div>
          </div>
          <div class="action-group">
            <button class="action-btn action-btn--contact" @click="handleContact">联系</button>
            <button class="action-btn action-btn--accept" @click="showConfirmation = true" :delegation="delegation">接单</button>
          </div>
          <div class="address-block">
            <img 
              src="../assets/icons/aimpoint.svg" 
              alt="定位" 
              class="address-icon"
              @error="handleImageError" 
              ref="addressIcon"
            />
            <div class="address-text">
              <div class="address-label">目的地</div>
              <div class="address-detail">{{ delegation.delivery_address }}</div>
            </div>
          </div>
        </div>
        <div class="info-grid">
          <div class="info-item">
            <label class="label">取件类型</label>
            <label class="info-value">{{ delegation.pickup_type === 1 ? '快递' : '外卖' }}</label>
          </div>
          
          <div class="info-item">
            <label class="label">取件方式</label>
            <label class="info-value">{{ delegation.pickup_method }}</label>
          </div>
          
          <div class="info-item">
            <label class="label">物件大小</label>
            <label class="info-value">{{ getSizeLabel(delegation.size) }}</label>
          </div>
        </div>
        
        <div class="info-grid">
          <div class="info-item">
            <label class="label">时间要求</label>
            <label class="info-value">{{ formatDateTime(delegation.limit_time) }}</label>
          </div>
          
          <div class="info-item">
            <label class="label">委托金额</label>
            <label class="info-value">¥{{ delegation.total_amount }}</label>
          </div>
          
          <div class="info-item">
            <label class="label">联系电话</label>
            <label class="info-value">{{ formatPhoneNumber(delegation.phone_number) }}</label>
          </div>
        </div>
        
        <div class="remarks-section">
          <label class="label">详细备注</label>
          <p class="remarks-content">{{ delegation.remarks || '暂无备注' }}</p>
          <p class="remarks-order-number" v-if="delegation.detail">单号: {{ delegation.detail }}</p>
        </div>
      </div>
    </div>
  </div>
  <ConfirmationDialog
    v-model:show="showConfirmation"
    :delegationId="delegation?.order_id"
    :senderId="delegation?.sender_id" 
    @confirm="handleConfirm"
    @cancel="handleCancel"
  />
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import ConfirmationDialog from '../views/ConfirmationDialog.vue'
import axios from 'axios'


const props = defineProps({
  show: Boolean,
  delegation: Object,
  clickPosition: Object
})

const isExpanded = ref(false)

// 监听 show 属性变化
watch(() => props.show, (newVal) => {
  if (newVal) {
    // 当显示时，先重置状态，然后用 nextTick 触发动画
    isExpanded.value = false
    requestAnimationFrame(() => {
      isExpanded.value = true
    })
  }
}, { immediate: true })

const close = () => {
  isExpanded.value = false
  setTimeout(() => {
    emit('update:show', false)
  }, 300)
}

const emit = defineEmits(['update:show'])

const showConfirmation = ref(false)

const router = useRouter()

const showErrorDialog = ref(false)

const closeErrorDialog = () => {
  showErrorDialog.value = false
}

const handleConfirm = async () => {
  try {
    var order_id = props.delegation.order_id
    if (props.delegation?.order_id) {
      const response = await axios.post('api/auth/accept', 
        {
          order_id: parseInt(order_id)
        },
        {
          headers: {
            'Authorization': localStorage.getItem('token'),
            'Content-Type': 'application/json',
          }
        }
      )
      
      console.log('接受委托响应:', response.code)
      if (response.code === 0) {
        sessionStorage.setItem('currentDelegation', JSON.stringify(props.delegation))
        
        router.replace({
          name: 'DelegationDetail',
          params: { id: String(order_id) },
          query: { timestamp: new Date().getTime() }
        })
      } else {
        console.error('接受委托失败:', response.data.message)
      }
    } else {
      console.error('Missing delegation id')
    }
  } catch (error) {
    console.error('处理接单请求时出错:', error)
  }
}

const handleCancel = () => {
  console.log('取消接单')
}

// 添加辅助函数
const getSizeLabel = (size) => {
  const sizeMap = {
    1: '小',
    2: '中',
    3: '大'
  }
  return sizeMap[size] || '未知'
}

const formatDateTime = (timestamp) => {
  if (!timestamp) return '无限制'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatPhoneNumber = (phone) => {
  if (!phone) return '暂无'
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
}

const handleContact = () => {
  if (props.delegation?.phone_number) {
    window.location.href = `tel:${props.delegation.phone_number}`
  }
}

// 添加图片加载错误处理
const handleImageError = (e) => {
  // 设置默认图片或移除图片
  e.target.src = '../assets/icons/default-location.svg' // 确保有这个默认图片
  // 或者隐藏图片
  // e.target.style.display = 'none'
}

// 添加 popupStyle 计算属性
const popupStyle = computed(() => {
  if (!props.clickPosition) {
    return {}
  }
  
  return {
    width: '100%',
    minHeight: '50vh',
    maxHeight: '90vh'
  }
})
</script>

<style scoped>

.delegation-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  background: var(--bg-overlay);
  z-index: 1000;
}

.delegation-content {
  position: fixed;
  background: linear-gradient(to bottom, var(--primary-color), var(--light-bg-color));
  border-radius: var(--border-radius-medium) var(--border-radius-medium) 0 0;
  overflow: hidden;
  transition: transform 0.3s ease-out;
  display: flex;
  flex-direction: column;
  box-shadow: var(--box-shadow);
  bottom: 0;
  left: 0;
  right: 0;
  height: 90vh;
  transform: translateY(100%);
  width: 100%;
  z-index: 1001; /* 确保在遮罩层上面 */
}

.delegation-content--expanded {
  transform: translateY(0) !important;
}



.address-container {
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
}

.address-block {
  display: flex;
  gap: 10px 0;
  padding: 10px 0;
}

.address-text {
  max-width: 120px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.address-label {
  /* text-align: left; */
  font-size: var(--font-size-xlarge);
  font-family: var(--font-family-bold);
  color: var(--text-light);
}

.address-detail {
  font-size: var(--font-size-large);
  color: var(--text-primary);
}

.address-icon {
  margin-top: 15px;
  width: 24px;
  height: 24px;
}

.action-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
  justify-content: center;
  padding: 5px;
}

.action-btn {
  width: 48px;
  height: 21px;
  padding: 0px 10px;
  border-radius: 20px;
  border: none;
  font-size: var(--font-size-small);
}

.action-btn--contact,
.action-btn--accept {
  background-color: var(--bg-white);
  color: var(--primary-color);
}

.delegation-close-btn {
  position: absolute;
  top: 10px;
  left: 10px; /* 改为左对齐 */
  cursor: pointer;
  color: #333;
}

.delegation-body {
  margin-top: 7%;
  flex: 1;
  overflow-y: auto;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-grid {
  display: flex;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  background: white;
  border-radius: var(--border-radius-medium);
  box-shadow: var(--box-shadow);
  margin: 5px 0;
}

.info-item {
  flex: 1;
  text-align: center;
  padding: 15px;
}

.label {
  display: flex;
  margin-bottom: 10px;
  font-size: var(--font-size-normal);
  color: #666;
}

.info-value {
  display: block;
  width: 100%;
  padding: 8px;
  font-size: var(--font-size-small);
  border-radius: 5px;
  background-color: rgba(154, 154, 154, 1);
  color: white;
  font-family: var(--font-family-bold);
}

.remarks-section {
  background-color: white;
  border-radius: var(--border-radius-medium);
  padding: 18px;
  margin-top: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}


.remarks-content,
.remarks-order-number {
  font-size: var(--font-size-small);
  color: #666;
  text-align: justify;
}

/* 添加错误提示弹窗样式 */
.error-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.error-content {
  background: white;
  padding: 20px;
  border-radius: 12px;
  width: 80%;
  max-width: 300px;
  text-align: center;
}

.error-content h3 {
  margin: 0 0 15px 0;
  color: var(--text-primary);
}

.error-content p {
  margin: 0 0 20px 0;
  color: var(--text-secondary);
}

.error-btn {
  padding: 8px 20px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.error-btn:hover {
  background-color: var(--primary-color-dark);
}
</style>